from django.shortcuts import render, redirect

from tools.form.form import UserModelForm
from tools.models import models
from django import forms

from tools.utils.PageData import PageData
from tools.utils.modelform import BootStrapModelForm


# def user_list(request):
#     """ 用户管理 """
#     # queryset = models.Department.objects.all()
#     # return render(request, "../templates/testdepart/depart_list.html", {'querySet':queryset})
#
#     # 获取所有用户列表[obj, obj, obj]
#     querySet = models.UserInfo.objects.all()
#
#     # for obj in querySet:
#     #     print(obj.id, obj.name, obj.account, obj.creatime.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display(), obj.depart_id)
#     #     print(obj.name, obj.depart_id)
#     #     # obj.depart_id  # 获取数据库中存储的那个字段值
#     #     # obj.testdepart.title  # 根据id自动去关联的表中获取哪一行数据depart对象
#
#     print('user_list的querySet',querySet)
#     return render(request, "../templates/testuser/user_list.html", {"querySet": querySet})
# #     # return render(request, "../templates/testuser/user_list.html", context)


def user_list(request):
    """用户列表"""
    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    page_object = PageData(request, queryset, page_size=20)

    # 用 python 的语法获取数据
    """
    for obj in user_data:
        # obj.get_gender_display() 表示匹配 男/女,原始字段名为gender,obj.get_字段名称_display()
        # obj.create_time.strftime("%Y-%m-%d") 表示将时间格式转换成固定格式的字符串
        # obj.depart.title 表示获取depart_id对应的部门名称,因为我们在models中定义表时与另外一张表设置了级联关系,有外键
        print(obj.id, obj.name, obj.password, obj.age, obj.account, obj.get_gender_display(), obj.depart.title, obj.create_time.strftime("%Y-%m-%d"))
    """

    page_string = page_object.page_html()

    context = {
        "querySet": page_object.page_queryset,
        "page_string": page_string,
    }

    return render(request, "../templates/testuser/user_list.html", context)


def user_add(request):
    """ 添加用户(ModelForm版本) """
    if request.method == "GET":
        context = {
            'gender_choice': models.UserInfo.gender_choice,
            'depart_list': models.Department.objects.all()
        }
        return render(request, "../templates/testuser/user_add.html", context)

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    ac = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age, account=ac,
                                   creatime=ctime, gender=gender, depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/tools/user/list/")


# ######################## ModelForm 示例 ########################
# ModelForm 提取到form.py

def user_model_form_add(request):
    """ 添加用户 ModelForm版本 """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, "../templates/testuser/user_model_form_add.html", {"form": form})

    # 用post提交数据，数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '程青松', 'password': '789', 'age': 88, 'account': Decimal('88888'), 'gender': 1, 'testdepart': <Department: IT测试部>}
        # print(form.cleaned_data)
        # models.UserInfo.objects.create(...)
        form.save()
        return redirect("/tools/user/list/")

    # 校验失败（在页面上显示错误信息）
    return render(request, "../templates/testuser/user_model_form_add.html", {"form": form})


def user_edit(request, nid):
    """ 修改用户 ModelForm版本 """
    row_object = models.UserInfo.objects.filter(id=nid).first()

    # GET请求
    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserModelForm(instance=row_object)
        return render(request, "../templates/testuser/user_edit.html", {"form": form})

    # POST请求
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的数据，如果想在用户输入以外增加一些值
        # form.instance.字段名 = 值
        form.save()
        return redirect("/tools/user/list/")
    return render(request, "../templates/testuser/user_edit.html", {"form": form})


def user_delete(request, nid):
    """ 删除用户 """
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/tools/user/list/")

